<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\index\controller;

use app\index\BaseController;
use app\service\cdz\YunKuaiChongService;
use app\service\jwt\YkcJwtService;
use Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;


/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class YunKuaiChong extends BaseController
{
    //云快充
    private $thirdStoreNumber = 'MA1MY0GF9';//云快充-组织机构代码(企业名称，营业执照)
    private $YKCService = 'vfkh4k740lfg88kq';//云快充-运营商秘钥（OperatorSecret）
    //本地企业
    private $storeNumber = 'MABTCJRN0';//企业-组织机构代码(企业名称，营业执照)
    //private $selfYKCService = '4ab29f74c0040c49';
    private $selfYKCService = 'a16caae825b5742c';//企业-运营商秘钥（OperatorSecret）
    private $testName = 'http://dev-zdl.ykccn.net/ZdlSuperviseServer/0/';
    //private $uatName = 'http://api-zdl.ykccn.net/ZdlSuperviseServer/0/';//测试
    private $uatName = 'http://cbss-api.ykccn.com/ZdlSuperviseServer/0/';//正式

    function test(){
        $result = $this->loginInfo();
        dump($result);
    }


    /**
     * 登录获取token
     */
    function loginInfo(){
        $YKCService = new YunKuaiChongService();
        $data = json_encode([
            'OperatorID'=>$this->storeNumber,
            'OperatorSecret'=>$this->YKCService,
        ]);
        $secretData = $YKCService->encrypt($data);
        $requestData = $this->getSignData($secretData);
        $sign = $YKCService->getSign($requestData);
        $requestData['Sig'] = $sign;
        //dump($requestData);
        $result = $YKCService->curlData($this->uatName."query_token",$requestData);
        //dump($result);
        if($result['code'] == 0 && $result['data']['Ret'] == 0 ){
            $setData = $YKCService->decrypt($result['data']['Data']);
            if($setData['SuccStat'] == 0){
                $saveData = [
                    'token'=>$setData['AccessToken'],
                    'available_time'=>time() + $setData['TokenAvailableTime'],
                    'operator_id'=>$this->storeNumber,
                    'create_time'=>date("Y-m-d H:i:s"),
                    'update_time'=>date("Y-m-d H:i:s"),
                ];
                $addId = Db::table('jy_ykc_token')->insertGetId($saveData);
                if($addId){
                    $saveData['id'] = $addId;
                    return ['code'=>0,'msg'=>'登录成功','data'=>$saveData];
                }else{
                    return ['code'=>1,'msg'=>'登录失败'];
                }
            }else{
                $addId = $this->addErrorInfo($result,'query_token',$result['data']['FailReason']);
                return ['code'=>2,'msg'=>'登录失败'];
            }
        }else{
            $addId = $this->addErrorInfo($result,'query_token');
            return ['code'=>3,'msg'=>'登录失败','data'=>isset($result['data']) ? $result['data'] : []];
        }
    }

    /**
     * 用于主动查询云快充的电站基础信息2.4
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function selectStationInfo(){
        $getToken = $this->getTokenInfo('query_stations_info');
        if($getToken['code'] > 0){
            return $this->fail($getToken['msg']);
            //return $getToken;
        }
        $tokenInfo = $getToken['data'];
        //查询充电站
        $data = json_encode(['LastQueryTime'=>'', 'PageNo'=>1, 'PageSize'=>200]);
        $YKCService = new YunKuaiChongService();
        $secretData = $YKCService->encrypt($data);
        $requestData = $this->getSignData($secretData);
        $sign = $YKCService->getSign($requestData);
        $requestData['Sig'] = $sign;
        $result = $YKCService->curlData($this->uatName."query_stations_info",$requestData,$tokenInfo['token']);
        //dump($result);
        if($result['code'] == 0 && isset($result['data']['Data'])){
            $setData = $YKCService->decrypt($result['data']['Data']);
            $stationList = $setData['StationInfos'];
            $addData = [];
            foreach ($stationList as $key=>$value){
                $checkWhere = ['operator_id'=>$value['OperatorID'],'station_id'=>$value['StationID'],'is_delete'=>0];
                $checkInfo =  Db::table('jy_ykc_station')->where($checkWhere)->find();
                if(!$checkInfo){
                    $addData[] = [
                        'operator_id'=>$value['OperatorID'],
                        'station_id'=>$value['StationID'],
                        'title'=>$value['StationName'],
                        'telephone'=>$value['StationTel'],
                        'picture'=>$value['Pictures'],
                        'address'=>$value['Address'],
                        'longitude'=>$value['StationLng'],
                        'latitude'=>$value['StationLat'],
                        'remark'=>isset($value['Remark']) ? $value['Remark'] : '',
                        'parking_remark'=>$value['ParkFee'],
                        'data'=>json_encode($value,JSON_UNESCAPED_UNICODE),
                        'is_delete'=>0,
                        'create_time'=>date("Y-m-d H:i:s"),
                        'update_time'=>date("Y-m-d H:i:s"),
                    ];
                }
            }
            //添加充电站
            if(!empty($addData)){
                $addResult = Db::table('jy_ykc_station')->insertAll($addData);
                return $this->success('查询成功');
                //return ['code'=>0,'msg'=>'查询成功'];
            }
        }else{
            $addId = $this->addErrorInfo($result,'query_stations_info');
            return $this->fail('查询失败');
            //return ['code'=>3,'msg'=>'查询失败'];
        }
    }

    //设备接口状态查询 2.5
    function selectDeviceInfo(){
        //获取token
        $getToken = $this->getTokenInfo('query_station_status');
        if($getToken['code'] > 0){
            return $this->fail($getToken['msg']);
            //return $getToken;
        }
        $tokenInfo = $getToken['data'];
        //获取充电站
        $where = ['is_delete'=>0];
        $stationInfo = Db::table('jy_ykc_station')->where($where)->column('station_id');
        $selectList = array_chunk($stationInfo,200);
        $YKCService = new YunKuaiChongService();
        foreach ($selectList as $key=>$value){
            $data = json_encode(['StationIDs'=>$value]);
            $secretData = $YKCService->encrypt($data);
            $requestData = $this->getSignData($secretData);
            $sign = $YKCService->getSign($requestData);
            $requestData['Sig'] = $sign;
            $result = $YKCService->curlData($this->uatName."query_station_status",$requestData,$tokenInfo['token']);
            //dump($result);
            //请求不到对应的数据
            if($result['code'] > 0){
                $this->addErrorInfo($result,'query_station_status');
            }else if($result['code'] == 0 && isset($result['data']['Data'])){
                $deviceList = $YKCService->decrypt($result['data']['Data']);
                foreach ($deviceList['StationStatusInfos'] as $key=>$value){
                    //设备端口记录
                    //$deviceWhere = ['station_id'=>$value['StationID']];
                    foreach ($value['ConnectorStatusInfos'] as $k=>$v){
                        $saveData = [
                            'is_status'=>$v['Status'],
                            'park_status'=>$v['ParkStatus'],
                            'lock_status'=>$v['LockStatus'],
                            'update_time'=>date("Y-m-d H:i:s"),
                        ];
                        $deviceInfo = Db::table('jy_ykc_device_info')->where('device_num',$v['ConnectorID'])->find();
                        if($deviceInfo){
                            if(!$deviceInfo['station_id']) $saveData['station_id'] = $value['StationID'];
                            Db::table('jy_ykc_device_info')->where('id',$deviceInfo['id'])->update($saveData);
                        }else{
                            $saveData['station_id'] = $value['StationID'];
                            $saveData['device_num'] = $v['ConnectorID'];
                            $saveData['create_time'] = date("Y-m-d H:i:s");
                            Db::table('jy_ykc_device_info')->insertGetId($saveData);
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加错误信息
     * @param $result
     * @param $selectType
     * @param string $errorInfo
     * @return int|string
     */
    function addErrorInfo($result,$selectType,$errorInfo='请求接口失败'){
        if(!isset($result['data'])) $result['data'] = '';
        $saveData = [
            'operator_id'=>$this->storeNumber,
            'data'=>is_array($result['data']) ? json_encode($result['data'],JSON_UNESCAPED_UNICODE) : $result['data'],
            'fail_info'=> $errorInfo,
            'request_info'=>$selectType,
            'create_time'=>date("Y-m-d H:i:s"),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $addId = Db::table('jy_ykc_request_error')->insertGetId($saveData);
        return $addId;
    }

    /**
     * 获取token信息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getTokenInfo($selectType){
        $tokenInfo = Db::table('jy_ykc_token')->where('operator_id',$this->storeNumber)
            ->where('available_time','>',time())->order('id','desc')->find();
        if(!$tokenInfo){
            $getTokenInfo = $this->loginInfo();
            if($getTokenInfo['code'] > 0){
                $addId = $this->addErrorInfo('获取不到对应的token',$selectType,'获取不到对应的token');
                return ['code'=>2,'msg'=>'获取不到对应token'];
            }
            $tokenInfo = $getTokenInfo['data'];
        }
        return ['code'=>0,'data'=>$tokenInfo,'msg'=>'获取成功'];
    }

    /**
     * 返回sign数据结构
     * @param $data
     * @return array
     */
    function getSignData($data){
        return [
            'OperatorID'=>$this->storeNumber,
            'Data'=>$data,
            'TimeStamp'=>date("YmdHis"),
            //'Seq'=>'0'.rand(100,999),
            'Seq'=>'0001',
        ];
    }

    /**************************  推送接口  **************************/
    /**
     * 第三方调用获取toke
     * @return $this
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    function queryToken(){

        $getData =  Request::post();
        $this->addThirdData($getData,'query_token');
//        $getData = Db::table('jy_third_put_data')->where('id',106)->value('put_data');
        //dump($getData);
        $setData = is_array($getData) ? $getData : json_decode($getData,true);
        $YKCService = new YunKuaiChongService();
        //验签
        $getSign = $YKCService->getSelfSign($setData);
        if($getSign != $setData['Sig']){
            $backData = [
                'code'=>'4001',
                'msg'=>'签名错误',
                'data'=>[
                    'OperatorID'=>$this->selfYKCService,
                    'SuccStat'=>1,
                    'AccessToken'=>'',
                    'TokenAvailableTime'=>'',
                    'FailReason'=>3,
                ],
            ];
            return json()->data($this->setSelfBackInfo($YKCService,$backData));
        }
        //解密参数内容
        $data = $YKCService->selfDecrypt($setData['Data']);
        if(!$data){
            $backData = [
                'code'=>'4004',
                'msg'=>'参数解密后错误',
                'data'=>[
                    'OperatorID'=>$this->selfYKCService,
                    'SuccStat'=>1,
                    'AccessToken'=>'',
                    'TokenAvailableTime'=>'',
                    'FailReason'=>3,
                ],
            ];
            return json()->data($this->setSelfBackInfo($YKCService,$backData));
        }
        if($data['OperatorID'] != $this->thirdStoreNumber || $data['OperatorSecret'] != $this->selfYKCService){
            $backData = [
                'code'=>'4004',
                'msg'=>'参数错误',
                'data'=>[
                    'OperatorID'=>$this->selfYKCService,
                    'SuccStat'=>1,
                    'AccessToken'=>'',
                    'TokenAvailableTime'=>'',
                    'FailReason'=>3,
                ],
            ];
            return json()->data($this->setSelfBackInfo($YKCService,$backData));
        }
        $jwtTokenService = new YkcJwtService();
        $tokenInfo = $jwtTokenService->createToken($data['OperatorID'],'ykc',strtotime("+ 30day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], (31 * 24 * 60 * 60));
        $backData = [
            'code'=>'0',
            'msg'=>'获取成功',
            'data'=>[
                'OperatorID'=>$data['OperatorID'],
                'SuccStat'=>0,
                'AccessToken'=>$tokenInfo['token'],
                'TokenAvailableTime'=>$tokenInfo['out'],
                'FailReason'=>0,
            ],
        ];
        //Log::info('登录后返回的token数据'.json_encode($backData));
        //dump($tokenInfo['token']);
        return json()->data($this->setSelfBackInfo($YKCService,$backData));
    }

    /**
     * 添加第三方推送数据
     * @param $getData
     * @param $put_type
     * @return int|string
     */
    function addThirdData($getData,$put_type){
        $saveData = [
            'order_sn'=>0,
            'put_data'=>is_array($getData) ? json_encode($getData,JSON_UNESCAPED_UNICODE) : $getData,
            'is_count'=>0,
            'put_type'=>$put_type,
            'create_time'=>date("Y-m-d H:i:s"),
        ];
        return Db::table('jy_third_put_data')->insertGetId($saveData);
    }

    /**
     * 设备状态变化推送
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function putDeviceInfo(){
        $getData =  Request::post();
        $this->addThirdData($getData,'notification_stationStatus');
        //$getData = Db::table('jy_third_put_data')->where('id',25)->value('put_data');
        $tokenInfo = $this->checkTokenInfo('notification_stationStatus');
        if($tokenInfo['code'] != 0){
            return json()->data($tokenInfo['back_data']);
        }
        $getData = is_array($getData) ? $getData : json_decode($getData,true);
        $checkData = $this->checkPutData($getData);
        $YKCService = new YunKuaiChongService();
        //dump($checkData);
        //数据验证成功
        if($checkData['code'] == 0){
            $backData = $checkData['data']['Data']['ConnectorStatusInfo'];
            //正常返回数据
            if(isset($backData['ConnectorID']) && isset($backData['Status'])){
                $deviceInfo = Db::table('jy_ykc_device_info')
                    ->where('device_num',$backData['ConnectorID'])->find();
                $saveData =[
                    'is_status'=>$backData['Status'],
                    'park_status'=>$backData['ParkStatus'],
                    'lock_status'=>$backData['LockStatus'],
                    'update_time'=>date("Y-m-d H:i:s"),
                ];
                if($deviceInfo){
                    $updateResult = Db::table('jy_ykc_device_info')->where('id',$deviceInfo['id'])->update($saveData);
                    if(!$updateResult) $this->addErrorInfo($checkData['data'],'notification_stationStatus','更新设备数据库信息失败');
                }else{
                    $saveData['station_id'] = 0;
                    $saveData['device_num'] = $backData['ConnectorID'];
                    $saveData['create_time'] = date("Y-m-d H:i:s");
                    $addResult = Db::table('jy_ykc_device_info')->insertGetId($saveData);
                    //dump($addResult);
                    //$this->addErrorInfo($checkData['data'],'notification_stationStatus','数据库没有对应的设备');
                }
            }else{
                $this->addErrorInfo($checkData['data'],'notification_stationStatus','数据解密失败');
            }
        //数据验证失败
        }else{
            $this->addErrorInfo($checkData,'notification_stationStatus','数据验证失败');
        }
        //数据返回
        $backData = [
            'code'=>'0',
            'msg'=>'推送成功',
            'data'=>['Status'=>0],
        ];
        //Log::info('返回设备的数据'.json_encode($backData));
        return json()->data($this->setSelfBackInfo($YKCService,$backData));
    }

    /**
     * 接受第三方推送的订单参数
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function putOrderInfo(){
        $data =  Request::post();
        $this->addThirdData($data,'notification_charge_order_info');
        $tokenInfo = $this->checkTokenInfo('notification_charge_order_info');
        if($tokenInfo['code'] != 0){
            return json()->data($tokenInfo['back_data']);
        }
        //$data = json_decode(Db::table('jy_third_put_data')->where('id',116)->value('put_data'),true);
        $checkData = $this->checkPutData($data);
        $orderResult = true;
        if($checkData['code'] == 0){
            $orderResult = $this->setOrder($checkData['data']['Data']);
        }else{
            $this->addErrorInfo($checkData,'notification_charge_order_info','数据验证失败');
        }
        //数据返回
        $backData = [
            'StartChargeSeq'=>isset($data['StartChargeSeq']) ? $data['StartChargeSeq'] : '',
            'ConnectorID'=>isset($data['ConnectorID']) ? $data['ConnectorID'] : '',
        ];
        if($orderResult){
            $backData['ConfirmResult'] = 0;
        }else{
            $backData['ConfirmResult'] = 2;
        }
        $setBackData = [
            'code'=>'0',
            'msg'=>'获取成功',
            'data'=>$backData,
        ];
        //Log::info('返回订单的数据'.json_encode($setBackData));
        //dump($tokenInfo['token']);
        $YKCService = new YunKuaiChongService();
        return json()->data($this->setSelfBackInfo($YKCService,$setBackData));
    }

    /**
     * 添加订单记录
     * @param $backData
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function setOrder($backData){
        $stationId = Db::table('jy_ykc_device_info')->where('device_num',$backData['ConnectorID'])->value('station_id');
        if(!$stationId) $stationId = 1;
        $chargeTime = number_format((strtotime($backData['EndTime']) - strtotime($backData['StartTime']))/60,2);
        $setChargeNumber = $backData['TotalPower'] * 1.1;//叠加系数累计充电量
        $setChargeCost = $backData['TotalElecMoney'];//叠加系数总电费
        $setServiceCost = $backData['TotalSeviceMoney'] * 1.1;//叠加系数总服务费
        $setTotalPrice =  $setChargeCost + $setServiceCost;//叠加系数累计总金额
        $setChargeTime =  $chargeTime;//叠加系数累计时间
        $orderData = [
            'order_sn'=>$backData['StartChargeSeq'],            //充电订单号
            'pile_gun_number'=>$backData['ConnectorID'],        //充电设备接口编码
            'start_time'=>$backData['StartTime'],               //开始充电时间
            'end_time'=>$backData['EndTime'],                   //结束充电时间
            'charge_number'=>$backData['TotalPower'],           //累计充电量
            'all_charge_cost'=>$backData['TotalElecMoney'],     //总电费
            'all_service_cost'=>$backData['TotalSeviceMoney'],  //总服务费
            'total_price'=>$backData['TotalMoney'],             //累计总金额
            'mark'=>$backData['StopReason'],                    //充电结束原因
            'charge_num'=>$backData['SumPeriod'],               //时段数 N
            'cout_pay_info'=>json_encode($backData['ChargeDetails']),   //充电明细信息
            'uid'=>0,                                           //用户id
            'user_phone'=>$backData['UserID'],                  //保存手机号
            'pile_id'=>0,
            'station_id'=>$stationId,
            'gun_id'=>0,
            'charge_cost'=>0,
            'service_cost'=>0,
            'peak_electric_cost'=>0,
            'peak_service_cost'=>0,
            'flat_electric_cost'=>0,
            'flat_service_cost'=>0,
            'valley_electric_cost'=>0,
            'valley_service_cost'=>0,
            'cost_id'=>0,
            'pile_price'=>0,
            'status'=>4,
            'charge_time'=>$chargeTime,
            'charge_end_content'=>json_encode($backData),
            'is_verify'=>0,
            'ratio_charge_number'=>$setChargeNumber,     //叠加系数累计充电量
            'ratio_charge_cost'=>$setChargeCost,         //叠加系数总电费
            'ratio_service_cost'=>$setServiceCost,      //叠加系数总服务费
            'ratio_total_price'=>$setTotalPrice,        //叠加系数累计总金额
            'ratio_charge_time'=>$setChargeTime,        //叠加系数累计时间
        ];
        $orderResultId = Db::table('jy_ykc_order')->insertGetId($orderData);
        /*
        //设置统计数据
        $stationInfo = Db::table('jy_station_data')->where('id',$stationId)->find();
        if($stationInfo && $orderResultId){
            $saveData = [
                'all_charge_electricity'=>$stationInfo['all_charge_electricity'] + $backData['TotalPower'],
                'all_charge_money'=>$stationInfo['all_charge_money'] + $backData['TotalMoney'],
                'all_charge_number'=>$stationInfo['all_charge_number'] +1,
                'all_charge_time'=>$stationInfo['all_charge_time'] + $chargeTime,
            ];
            Db::startTrans();
            $dataResult = Db::table('jy_station_data')->where('id',$stationId)->update($saveData);
            $orderResult = Db::table('jy_ykc_order')->where('id',$orderResultId)->update(['is_verify'=>1,'update_time'=>date("Y-m-d H:i:s")]);
            if($dataResult && $orderResult){
                Db::commit();
            }else{
                Db::rollBack();
            }
        }
        */
        return $orderResultId;
    }

    /**
     * 推送数据验证
     * @param $getData
     * @return array
     */
    function checkPutData($getData){
        if(!isset($getData['OperatorID']) || $getData['OperatorID'] != $this->thirdStoreNumber) return ['code'=>1,'msg'=>'运营商标识错误'];
        $YKCService = new YunKuaiChongService();
        $getSign = $YKCService->getSelfSign($getData);
        if($getSign != $getData['Sig']) return ['code'=>2,'msg'=>'秘钥验证失败'];
        //解密参数内容
        $decryptData = $YKCService->selfDecrypt($getData['Data']);
        if(!$decryptData)  return ['code'=>3,'msg'=>'内容解密失败'];
        $data = is_array($decryptData) ? $decryptData : json_decode($decryptData,true);
        if(!$data) return ['code'=>4,'msg'=>'数据解析失败'];
        $getData['Data'] = $data;
        return ['code'=>0,'msg'=>'数据验证成功','data'=>$getData];
    }

    /**
     * 推送信息token验证
     * @return array
     */
    function checkTokenInfo($queryType){
        $tokenService = new YkcJwtService();
        $tokenInfo = $tokenService->getTokenInfo();

        if($tokenInfo['code'] != 0){
            $backData = [
                'code'=>'4002',
                'msg'=>'token错误',
                'data'=>[
                    'status'=>'4002',
                    'error'=>'token Error',
                ],
            ];
            $YKCService = new YunKuaiChongService();
            $backData = $this->setSelfBackInfo($YKCService,$backData);
            return ['code'=>1,'back_data'=>$backData];
        }
        return $tokenInfo;
    }

    /**
     * 设置返回内容
     * @param $YKCService
     * @param $backData
     * @return $this
     */
    function setSelfBackInfo($YKCService,$backData){
        $secretData = $YKCService->selfEncrypt($backData['data']);
        $setBackData =  [
            'Ret'=>$backData['code'],
            'Data'=>$secretData,
            'Msg'=>$backData['msg'],
        ];
        $sign = $YKCService->getSelfBackSign($setBackData);
        $setBackData['Sig'] = $sign;
        //$setBackData = json_encode($setBackData);
        //dump($setBackData);
        return $setBackData;
    }

    /**************************  定时器查询  **************************/

    //定时器查询
    function timeSelect(){
        //统计充电枪在线状态
        $this->countGun();
        sleep(1);
        $this->orderCount();

    }
    //每小时调用频率
    function houseSelect(){
        $getHouse = date("H");
        if($getHouse % 2 == 0){
            $this->selectDeviceInfo();
        }
        if($getHouse % 3 == 0){
            $this->selectStationInfo();
        }
        if($getHouse == 0 || $getHouse == '00' || $getHouse == '24'){
            $this->addDayRecord();
        }
    }

    /**
     * 统计枪的状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function countGun(){
        $stationList = Db::table('jy_ykc_station')->where('is_delete',0)->select()->toArray();
        foreach ($stationList as $key=>$value){
            if($value['relation_id']){
                $countWhere = ['station_id'=>$value['station_id']];
                $saveData = ['update_time'=>date("Y-m-d H:i:s")];
                $saveData['gun_number'] = Db::table('jy_ykc_device_info')->where($countWhere)->count();
                $saveData['gun_use'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',3)->count();
                $saveData['gun_off_line'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',0)->count();
                $saveData['gun_idle'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',1)->count();
                $saveData['gun_appointment'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',4)->count();
                $saveData['gun_fault'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',255)->count();
                $saveData['gun_floor_use'] = Db::table('jy_ykc_device_info')->where($countWhere)->where('is_status',2)->count();
                $stationData = Db::table('jy_station_data')->where('station_id',$value['relation_id'])->find();
                if($stationData){
                    $result =  Db::table('jy_station_data')->where('station_id',$value['relation_id'])->update($saveData);
                }else{
                    $saveData['station_id'] = $value['relation_id'];
                    $saveData['create_time'] = date("Y-m-d H:i:s");
                    $result =  Db::table('jy_station_data')->insertGetId($saveData);
                }
            }
        }
    }

    //订单数据统计
    function orderCount(){
        $where = ['is_verify'=>0,'is_del'=>0,'is_system_del'=>0];
        $orderList = Db::table('jy_ykc_order')->where($where)->where('end_time','<>','')->select()->toArray();
        foreach ($orderList as $key=>$value){
            //获取枪和站点对应的信息
            $gunInfo = Db::table('jy_ykc_device_info')->where('device_num',$value['pile_gun_number'])->find();
            $stationInfo = false;
            if($gunInfo){
                $stationInfo =  Db::table('jy_ykc_station')->where('is_delete',0)->where('station_id',$gunInfo['station_id'])->find();
            }
            if((!$gunInfo || !$stationInfo || !$stationInfo['relation_id']) && strtotime($value['end_time']) < (time() - 2 * 24 * 60 * 60) ){
                $saveOrderData = ['is_verify'=>2,'update_time'=>date("Y-m-d H:i:s")];
                $result = Db::table('jy_ykc_order')->where('id',$value['id'])->update($saveOrderData);
            }else{
                //进行统计
                if($gunInfo && $stationInfo && $stationInfo['relation_id']){
                    //获取站点数据
                    $stationData = Db::table('jy_station_data')->where('station_id',$stationInfo['relation_id'])->find();
                    if(!$stationData){
                        $stationData = $this->addStationData($stationInfo);
                    }
                    if($stationData){
                        //获取站点日记录数据
                        $where = ['station_id'=>$stationData['station_id'],'day_data'=>date("Y-m-d",strtotime($value['end_time']))];
                        $dayData = Db::table('jy_station_day_data')->where($where)->find();
                        if(!$dayData){
                            $dayData = $this->addStationDayData($stationData,$value);
                        }
                        //统计对应的数据
                        if($dayData){
                            $saveStation = [
                                'all_charge_electricity'=>$stationData['all_charge_electricity'] + $value['ratio_charge_number'],
                                'all_charge_money'=>$stationData['all_charge_money'] + $value['ratio_total_price'],
                                'all_charge_number'=>$stationData['all_charge_number'] + 1,
                                'all_charge_time'=>$stationData['all_charge_time'] + number_format(($value['ratio_charge_time']/60),3),
                                'update_time'=>date("Y-m-d H:i:s"),
                                'real_charge_electricity'=>$stationData['real_charge_electricity'] + $value['charge_number'],
                                'real_charge_money'=>$stationData['real_charge_money'] +  $value['total_price'],
                                'real_charge_number'=>$stationData['real_charge_number'] + 1,
                                'real_charge_time'=>$stationData['real_charge_time'] + number_format(($value['charge_time']/60),3),
                                'real_service_cost'=>$stationData['real_service_cost'] + $value['all_service_cost'],
                                'real_charge_cost'=>$stationData['real_charge_cost'] + $value['all_charge_cost'],
                            ];
                            $saveDayStation = [
                                'charge_electricity'=>$dayData['charge_electricity'] + $value['ratio_charge_number'],
                                'charge_money'=>$dayData['charge_money'] + $value['ratio_total_price'],
                                'charge_number'=>$dayData['charge_number'] + 1,
                                'charge_time'=>$dayData['charge_time'] + number_format(($value['ratio_charge_time']/60),3),
                                'update_time'=>date("Y-m-d H:i:s"),
                                'real_charge_electricity'=>$dayData['real_charge_electricity'] + $value['charge_number'],
                                'real_charge_money'=>$dayData['real_charge_money'] +  $value['total_price'],
                                'real_charge_number'=>$dayData['real_charge_number'] + 1,
                                'real_charge_time'=>$dayData['real_charge_time'] + number_format(($value['charge_time']/60),3),
                                'real_service_cost'=>$dayData['real_service_cost'] + $value['all_service_cost'],
                                'real_charge_cost'=>$dayData['real_charge_cost'] + $value['all_charge_cost'],
                            ];
                            $saveOrderData = ['is_verify'=>1,'update_time'=>date("Y-m-d H:i:s")];
                            Db::startTrans();
                            $stationResult = Db::table('jy_station_data')->where('id',$stationData['id'])->update($saveStation);
                            $stationDayResult = Db::table('jy_station_day_data')->where('id',$dayData['id'])->update($saveDayStation);
                            $result = Db::table('jy_ykc_order')->where('id',$value['id'])->update($saveOrderData);
                            if($stationResult && $stationDayResult && $result){
                                Db::commit();
                            }else{
                                Db::rollback();
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加站点记录
     * @param $stationInfo
     * @return array|bool
     */
    function addStationData($stationInfo){
        $addData = [
            'station_id'=>$stationInfo['relation_id'],
            'all_charge_electricity'=>0,
            'all_charge_money'=>0,
            'all_charge_number'=>0,
            'all_charge_time'=>0,
            'carbon_dioxide_number'=>0,
            'tree_planting_number'=>0,
            'gun_number'=>0,
            'gun_use'=>0,
            'gun_off_line'=>0,
            'gun_idle'=>0,
            'gun_appointment'=>0,
            'gun_fault'=>0,
            'gun_floor_use'=>0,
            'create_time'=>date("Y-m-d H:i:s"),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $addId = Db::table('jy_station_data')->insertGetId($addData);
        if($addId){
            $stationData = $addData;
            $stationData['id'] = $addId;
            return $stationData;
        }else{
            return false;
        }
    }

    /**
     * 添加站点日记录
     * @return array|bool
     */
    function addStationDayData($stationData,$value){
        $addDayData = [
            'station_id'=>$stationData['station_id'],
            'day_data'=>date("Y-m-d",strtotime($value['end_time'])),
            'charge_electricity'=>0,
            'charge_money'=>0,
            'charge_number'=>0,
            'charge_time'=>0,
            'carbon_dioxide_number'=>0,
            'tree_planting_number'=>0,
            'create_time'=>date("Y-m-d H:i:s"),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $addDayId =  Db::table('jy_station_day_data')->insertGetId($addDayData);
        if($addDayId){
            $dayData = $addDayData;
            $dayData['id'] = $addDayId;
            return $dayData;
        }else{
            return false;
        }
    }

    /**
     * 添加日常记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function addDayRecord(){
        $stationList = Db::table("jy_ykc_station")->where('is_delete',0)->select();
        $dayData = date("Y-m-d");
        $where = ['day_data'=>$dayData];
        foreach ($stationList as $key=>$value){
            $result = Db::table('jy_station_day_data')->where($where)->where('station_id',$value['relation_id'])->find();
            if(!$result){
                $addDayData = [
                    'station_id'=>$value['relation_id'],
                    'day_data'=>$dayData,
                    'charge_electricity'=>0,
                    'charge_money'=>0,
                    'charge_number'=>0,
                    'charge_time'=>0,
                    'carbon_dioxide_number'=>0,
                    'tree_planting_number'=>0,
                    'create_time'=>date("Y-m-d H:i:s"),
                    'update_time'=>date("Y-m-d H:i:s"),
                ];
                $addDayId =  Db::table('jy_station_day_data')->insertGetId($addDayData);
            }
        }


    }

}
